<?php

namespace addons\facrm\controller\facrm\contract;

use addons\facrm\library\BackendApi;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 回款计划
 *
 * @icon fa fa-circle-o
 */
class Plan extends BackendApi
{

    protected $noNeedRight = ["select"];
    /**
     * Plan模型对象
     * @var \app\admin\model\facrm\contract\Plan
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\contract\Plan;
        $this->request->filter(['strip_tags']);
    }

    /**
     * 回款计划列表
     * @ApiBody ("其它参数参考电脑版")
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;


        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];

        if (isset($filter['plan_time']) && strtotime($filter['plan_time'])) {
            $time = time();
            $filter_w['plan_time'] = ['<', \think\Db::raw(" ({$time}+(`remind_day`*86400))")];
            $filter_w['plan.status'] = ['neq', 2];
            unset($filter['plan_time']);
            $this->request->get(['filter' => json_encode($filter)]);
        }


        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        if (!$this->auth->isSuperAdmin() && !$this->auth->check('facrm/contract/index/index')) {
            $this->model->where('contract.order_admin_id', 'in', $this->auth->getChildrenAdminIds(true));
        }
	
        $list = $this->model
            ->with(['contract', 'customer', 'admin'])
            ->where($where)
            ->where($filter_w)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as $row) {

            $row->getRelation('contract')->visible(['name', 'id', 'number']);
            $row->getRelation('customer')->visible(['name', 'id']);
            $row->getRelation('admin')->visible(['nickname', 'id']);

        }

        $result = array("total" => $list->total(), "rows" => $list->items());
        $this->success('', $result);
    }

    /**
     * 添加
     * @ApiMethod (POST|GET)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户id")
     * @ApiParams(name="contract_id", type="int", required=true, description="合同id")
     * @ApiParams(name="number", type="string", required=true, description="回款编号")
     * @ApiParams(name="money", type="int", required=true, description="回款金额")
     * @ApiParams(name="account_id", type="int", required=true, description="收款账户")
     * @ApiParams(name="remind_day", type="int", required=true, description="提前提醒天数，默认1天")
     * @ApiParams(name="remark", type="string", required=false, description="备注")
     * @ApiParams(name="plan_time", type="string", required=true, description="计划回款时间,2023-12-30")
     * @ApiParams(name="name", type="string", required=true, description="业务名称")
     * @ApiBody ("")
     */
    public function add($contract_id = NULL)
    {
        $params = $this->request->post();
        if (empty($params)||!isset($params['contract_id'])) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkContractAuth($params['contract_id'], $this->auth, 'all')) {
            $this->error(__('您没有该合同的权限'));
        }
        $params['admin_id'] = $this->auth->id;

        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException$e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success('',['plan_id'=> $this->model->id]);
        } else {
            $this->error(__('No rows were inserted'));
        }
    }

    /**
     * 修改
     * @ApiMethod (POST|GET)
     * @ApiParams(name="id", type="int", required=true, description="计划id")
     * @ApiParams(name="customer_id", type="int", required=false, description="客户id")
     * @ApiParams(name="number", type="string", required=false, description="回款编号")
     * @ApiParams(name="contract_id", type="int", required=false, description="合同id")
     * @ApiParams(name="account_id", type="int", required=false, description="收款账户")
     * @ApiParams(name="money", type="int", required=false, description="回款金额")
     * @ApiParams(name="return_time", type="string", required=false, description="回款日期")
     * @ApiParams(name="flow_admin_id", type="int", required=false, description="审批人ID，多个逗号隔开")
     * @ApiParams(name="remark", type="string", required=false, description="备注")
     * @ApiBody ("get是获取，post是提交修改，更多参数参考电脑版")
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->auth->isSuperAdmin() && !$this->auth->check('facrm/contract/index/index') && !in_array($row->contract->order_admin_id, $this->auth->getChildrenAdminIds(true))) {
            $this->error(__('您没有权限修改'));
        }

        if (false === $this->request->isPost()) {
            $this->success('',$row);
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
      
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }



    /**
     * 选择回款计划
     * @ApiMethod (GET)
     * @ApiParams(name="contract_id", type="int", required=true, description="合同ID")
     */
    public function select()
    {
        $contract_id = $this->request->request('contract_id', '', 'intval');
        $contractModel =new \app\admin\model\facrm\Contract();
        $contract = $contractModel->find($contract_id);
        if (!$contract) {
            $this->error(__('合同不存在'));
        }
        $auth = new \addons\facrm\library\Auth();
        if (!$auth->checkContractAuth($contract, $this->auth, 'all')) {
            $this->error(__('您没有该合同的权限'));
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $filter = $this->request->request('filter');
        $filterArr = (array)json_decode($filter, true);
        $filterArr['contract_id'] = $contract_id;
        $this->request->get(['filter' => json_encode($filterArr)]);

        return $this->index();


    }

}
